import uuid
import os

from starlette.responses import FileResponse
from fastapi import APIRouter, UploadFile, Request, Form, Query
from app.parameter import UpdateUserInfoParam
from app.service import UserService, FileService
from app.constant import ERRORCODE
from app.config import DEFAULT_STATIC_PATH
from app.utils import Response,getUserInfo,tokenDecode
from app.service import DatabaseService
router = APIRouter(tags=["上传文件相关路由"])
from utils import DEBUG
import datetime

## 上传头像
@router.post('/upload/avatar')
async def uploadAvatar(file: UploadFile, request :Request):
    path = datetime.datetime.now().strftime("%Y-%m")
    # uuid1是时间戳+MAC地址
    # uuid4是随机数
    filename = str(uuid.uuid1()) + str(uuid.uuid4())+"."+file.filename.split(".")[-1]
    
    filepath = DEFAULT_STATIC_PATH + "/avatar/" + path
    if not os.path.isdir(filepath):
        os.makedirs(filepath)
    
    filepath = filepath + "/" + filename
    
    contents = await file.read()
    
    with open(filepath, "wb") as f:
        f.write(contents)
    
    filename = path + "/" + filename
    
    updateParam = UpdateUserInfoParam(userId = request.scope["token_data"]["id"], avatar=filename) 
    
    return UserService.updateUserInfo(updateParam)

## 上传文档
@router.post('/upload/document')
async def uploadDocument(request :Request, file: UploadFile, hubId: int = Form()):
    DEBUG(hubId)
    DEBUG(file)    
    userId = getUserInfo(request) 
    DEBUG(userId)
    res = await FileService.createFile(file, hubId, userId)
    return res

## 下载文档
@router.get('/download/document')
async def dowloadDocument(hubId: int=Query(), fileId: int=Query(), token:str = Query()):
    data, _ = tokenDecode(token)
    if data == None:
        return Response(ERRORCODE.REQUEST_UNAUTHORIZATION_ERROR)
    userId = data['id']
    print(hubId, fileId, userId)
    # filepath = "./knowledge/6/2/分布式消息队列RocketMQ.pdf"
    # filename = "分布式消息队列RocketMQ.pdf"
    # return FileResponse(path=filepath,filename=filename)
    res = await FileService.downloadFile(userId, hubId, fileId)
    return res